﻿using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Input;
using WickedFlame.Core.Shapes;
using System.Windows.Media;
using System.Windows;
using WickedFlame.Core.Layers;

namespace WickedFlame.Core.Layers
{
    public delegate void ShapeChangedEventHandler(object sender, ShapeChangedEventArgs e);

	public class CanvasLayer : Layer
	{
        public event ShapeChangedEventHandler ShapeChanged;
        public event ShapeChangedEventHandler ShapeMoved;
        public event ShapeChangedEventHandler ShapeAdded;
        public event ShapeChangedEventHandler ShapeDeleted;
        public event ShapeChangedEventHandler EndShapeChange;

        public override void AddShape(DrawableShape shape)
        {
            base.AddShape(shape);

            shape.ShapeMoved += new ChangedEventHandler(OnShapeMoved);
            shape.ShapeSizeChanged += new ChangedEventHandler(OnShapeChanged);
            shape.ShapeChangeEnd += new ChangedEventHandler(OnEndShapeChange);

            if (ShapeAdded != null)
                ShapeAdded(this, new ShapeChangedEventArgs(shape));
        }

        public override void RemoveShape(VectorShape shape)
        {
            base.RemoveShape(shape);
        
            if (ShapeDeleted != null)
                ShapeDeleted(this, new ShapeChangedEventArgs(shape));
        }

        public virtual void RemoveSelection()
        {
            var shapes = new List<VectorShape>();
            foreach (VectorShape shape in ShapeList)
            {
                if (shape.IsSelected)
                {
                    shapes.Add(shape);
                }
            }

            foreach (VectorShape shape in shapes)
            {
                ShapeList.Remove(shape);

                if (ShapeDeleted != null)
                    ShapeDeleted(this, new ShapeChangedEventArgs(shape));

            }
        }

        private void OnShapeChanged(object sender, EventArgs e)
        {
            if (ShapeChanged != null)
                ShapeChanged(this, new ShapeChangedEventArgs(sender as VectorShape));
        }

        private void OnShapeMoved(object sender, EventArgs e)
        {
            if (ShapeMoved != null)
                ShapeMoved(this, new ShapeChangedEventArgs(sender as VectorShape));
        }
        private void OnEndShapeChange(object sender, EventArgs e)
        {
            if (EndShapeChange != null)
                EndShapeChange(this, new ShapeChangedEventArgs(sender as VectorShape));
        }
    }
}
